<template>
  <div class="incoming-list">
    <!-- 搜索条件区域（优化布局+新增查询项） -->
    <el-form :inline="true" class="search-form" label-width="80px">
      <el-form-item label="文件标题">
        <el-input v-model="query.title" placeholder="请输入文件标题" style="width: 200px"></el-input>
      </el-form-item>

      <el-form-item label="发文单位">
        <el-input v-model="query.senderOrg" placeholder="请输入发文单位" style="width: 200px"></el-input>
      </el-form-item>

      <el-form-item label="密级">
        <el-select v-model="query.secretLevel" placeholder="请选择密级" style="width: 180px">
          <el-option label="普通" value="普通"></el-option>
          <el-option label="秘密" value="秘密"></el-option>
          <el-option label="机密" value="机密"></el-option>
          <el-option label="绝密" value="绝密"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="处理状态">
        <el-select v-model="query.archiveStatus" placeholder="请选择处理状态" style="width: 180px">
          <el-option label="未处理" value="未处理"></el-option>
          <el-option label="处理中" value="处理中"></el-option>
        </el-select>
      </el-form-item>

      <!--      <el-form-item label="存档日期">-->
      <!--        <el-date-picker-->
      <!--            v-model="query.archiveDate"-->
      <!--            type="date"-->
      <!--            placeholder="选择日期"-->
      <!--            style="width: 280px"-->
      <!--        ></el-date-picker>-->
      <!--      </el-form-item>-->

      <el-form-item>
        <el-button type="info" plain @click="loadData(1)">查询</el-button>
        <el-button type="warning" plain style="margin-left: 10px" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="toolbar" style="margin: 20px 0">
      <el-button type="info" @click="handleExport">导出</el-button>
    </div>

    <el-table
        :data="tableData"
        stripe
        border
        @selection-change="handleSelectionChange"
        style="width: 100%; margin-top: 20px"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="senderDocNo" label="发文编号" width="100"></el-table-column>
      <el-table-column prop="fileNo" label="件号" width="100"></el-table-column>
      <el-table-column prop="title" label="文件标题" width="220"></el-table-column>
      <el-table-column prop="senderOrg" label="发文单位" width="180"></el-table-column>
      <el-table-column prop="secretLevel" label="密级" width="100"></el-table-column>
      <el-table-column prop="createDate" label="发文日期" width="120">
        <template v-slot="scope">
          <div>{{ formatDate(scope.row.createDate) }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="handlingOrg" label="办件单位" width="180"></el-table-column>
      <el-table-column prop="archiveStatus" label="处理状态" width="80"></el-table-column>
      <el-table-column label="当前审批人" width="140">
        <template v-slot="scope">
          <div class="current-approver" :class="{'approver-waiting': !scope.row.nextObjectName}">
            {{ scope.row.nextObjectName || scope.row.objectName || '未分配' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="打印" width="140">
        <template v-slot="scope">
          <el-button :id="scope.row.id" type="warning" size="mini" @click="handlePrint(scope.row.id)">打印处理单</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240">
        <template v-slot="scope">
          <el-button size="mini" @click="handleDetail(scope.row.id)">详情</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        :current-page="pageNum"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total"
        @current-change="handlePageChange"
        style="margin-top: 30px"
    ></el-pagination>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'
export default {
  data() {
    return {
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      selectedIds: [],
      selectedRows: [],
      // 查询条件对象（与后端IncomingDoc实体字段对应）
      query: {
        title: '',          // 文件标题（模糊查询）
        senderOrg: '',      // 来文单位（模糊查询）
        archiveStatus: '',    // 处理状态（精确查询）
        secretType: null, // 密件类型（0-普通件，1-密件）
        archiveDate: null
      }
    };
  },
  created() {
    this.query.secretType = parseInt(this.$route.params.secretType);
    // 初始化加载第一页数据
    this.loadData(1);
  },
  watch: {
    // 监听路由参数变化
    $route(to) {
      this.query.secretType = parseInt(to.params.secretType);
      this.loadData(1);
    }
  },
  methods: {
    // 加载分页数据（核心逻辑）
    loadData(pageNum) {
      if (pageNum) this.pageNum = pageNum;
      // 调用后端分页接口，传递查询条件、页码、页大小
      this.$request.get('/outgoingDoc/selectHistoryPage', {
        params: {
          ...this.query,
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          archiveStatus: '存档',
          // 展开查询条件（与后端IncomingDoc实体字段一一对应）
        }
      }).then(res => {
        if (res.code === '200') {
          let dataList = res.data.list;
          if (dataList != null || dataList.length > 0) {
            console.log("dataList", dataList)
            dataList.forEach(item => {
              item.objectName = item.objectName === '办公室' ? "未处理" : item.objectName;
            })
            this.tableData = dataList;    // 表格数据
            this.total = res.data.total;       // 总条数（用于分页）
          } else {
            this.tableData = [];
            this.total = 0;
          }
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    // 重置查询条件
    resetQuery() {
      this.query = {
        title: '',
        senderOrg: '',
        archiveStatus: '',
        secretType: null, // 密件类型（0-普通件，1-密件）
        archiveDate: null,
      };
      this.loadData(1);  // 重置后重新加载第一页
    },

    // 分页页码变化
    handlePageChange(pageNum) {
      this.loadData(pageNum);
    },

    handleAdd() {
      this.$router.push(`/outgoing-doc-register/${this.query.secretType}`);
    },

    handleDetail(id) {
      this.$router.push(`/history-outgoing-doc-detail/${id}`);
    },
    handleEdit(row) {
      console.log("row", row)
      if (row.archiveStatus === "存档") {
        this.$message.warning("该发文已存档，不能编辑");
        return;
      }
      this.$router.push(`/outgoing-doc-edit/${row.id}/${this.query.secretType}`);
    },
    handleDelete(row) {
      if (row.archiveStatus === "存档") {
        this.$message.warning("该发文已存档，不能删除");
        return;
      }
      this.$confirm('确定删除该发文？', '提示', {type: 'warning'})
          .then(() => {
            this.$request.delete(`/outgoingDoc/delete/${row.id}`).then(res => {
              if (res.code === '200') {
                this.$message.success('删除成功');
                this.loadData(this.pageNum);  // 删除后刷新当前页
              } else {
                this.$message.error(res.msg);
              }
            }).catch(err => {
              this.$message.error(err.message);
            });
          })
          .catch(() => {
            this.$message.info('取消删除');
          });
    },
    handleArchive() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请选择需要存档的发文');
        return;
      }
      this.$confirm('确定批量存档选中的发文？', '提示', {type: 'warning'})
          .then(() => {
            // 假设后端支持批量存档（需与后端确认接口）
            // 这里示例使用循环调用单个存档接口，实际可优化为批量接口
            Promise.all(this.selectedIds.map(id =>
                this.$request.put(`/outgoingDoc/archive/${id}`)
            )).then(() => {
              this.$message.success('批量存档成功');
              this.loadData(this.pageNum);  // 刷新当前页
            });
          });
    },
    handlePrint(id) {
      const tpl_name = "收发文新系统.ureport.xml";
      const pageIndex = 1;     // 页码
      const renderOption = 1;  // 渲染选项
      const url = `${this.$baseUrl}/ureport/preview?_u=mysql:${tpl_name}&_i=${pageIndex}&_r=${renderOption}&ids=${id}`;
      window.open(url, '_blank');
      document.getElementById(id).blur();
    },
    handleSelectionChange(rows) {
      this.selectedIds = rows.map(row => row.id);
      this.selectedRows = rows;
    },
    handleExport() {
      let dataToExport;
      console.log(this.selectedRows)
      if (this.selectedRows.length > 0) {
        dataToExport = this.selectedRows
        this.exportToExcel(dataToExport, '发文数据_选中项')
      } else {
        let ExportQueryParams = {
          pageNum: 1,
          pageSize: 10000000,
          archiveStatus: '存档',
          ...this.query
        }
        this.$request.get('/outgoingDoc/selectHistoryPage', {
          params: ExportQueryParams
        }).then(res => {
          if (res.code === '200') {
            dataToExport = res.data.list
            this.exportToExcel(dataToExport, '发文数据_全部')
          } else {
            this.$message.error('获取导出数据失败：' + res.msg);
          }
        }).catch(err => {
          this.$message.error('导出失败: ' + err.message)
        });
      }
    },
    exportToExcel(data, fileName = '发文数据') {
      if (!data || data.length === 0) {
        this.$message.warning('无数据可导出');
        return;
      }

      // 定义表头映射关系
      const exportData = data.map(item => {
        return {
          '发文编号': item.senderDocNo || '',
          '文件标题': item.title || '',
          '发文单位': item.senderOrg || '',
          '密级': item.secretLevel || '',
          '存档日期': item.archiveDate || '',
          '办件单位': item.handlingOrg || '',
          '处理状态': item.archiveStatus || '',
          '当前审批人': item.nextObjectName || item.objectName || '未分配'
        };
      });

      const wb = XLSX.utils.book_new();
      const ws = XLSX.utils.json_to_sheet(exportData);

      const colWidths = [
        {wch: 15}, // 发文编号
        {wch: 25}, // 文件标题
        {wch: 20}, // 发文单位
        {wch: 10}, // 密级
        {wch: 12}, // 存档日期
        {wch: 20}, // 办件单位
        {wch: 10}, // 处理状态
        {wch: 15}  // 当前审批人
      ]
      ws['!cols'] = colWidths;
      XLSX.utils.book_append_sheet(wb, ws, '发文数据');
      const exportFileName = `${fileName}_${new Date().toISOString().slice(0, 10)}.xlsx`;
      XLSX.writeFile(wb, exportFileName);
    },
    formatDate(dateString) {
      if (!dateString) return '';
      return dateString.split(' ')[0];
    },
  }
};
</script>

<style scoped>
/* 优化搜索区域样式 */
.search-form {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-top: 20px;
}

/* 调整表格列间距 */
.el-table .el-table__cell {
  padding: 12px 0;
}

/* 工具栏按钮间距 */
.toolbar .el-button {
  margin-right: 10px;
}
.current-approver {
  padding: 4px 8px;
  background: #e6f7ff;
  border-radius: 3px;
  color: #1890ff;
  display: inline-block;
}

.approver-waiting {
  background: #fff7e6;
  color: #fa8c16;
}
</style>

